<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!---->
        <el-card>
            <el-button type="primary" @click="dialogAddVisible = true">添加角色</el-button>
            <el-table :data="roleList" style="width: 100%" border stripe>
                <!--展开行-->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!--渲染一级权限-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--渲染二级和三级权限-->
                            <el-col :span="19">
                                <el-row :class="[i2!==0?'bdtop':'','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="dialogEditShow(scope.row.id, scope.row.mg_state)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="dialogSetRightShow(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog title="添加角色" :visible.sync="dialogAddVisible" @close="dialogAddClose">
            <el-form :model="newRole" :rules="newRoleRules" ref="newRoleRef" :label-width="formLabelWitdh">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="newRole.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="newRole.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="编辑角色信息" :visible.sync="dialogEditVisible" @close="dialogEditClose">
            <el-form :model="editRole" :rules="newRoleRules" ref="editRoleRef" :label-width="formLabelWitdh">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRole.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRole.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleEdit()">确 定</el-button>
            </div>
        </el-dialog>
        <!--分配权限弹窗-->
        <el-dialog title="分配权限" :visible.sync="dialogSetRightVisible" @close="dialogSetRightClose" width="50%">
            <el-tree :data="rightList" show-checkbox node-key="id" :default-expanded-keys="[2]" default-expand-all :default-checked-keys="defaultKeys"
  :props="defaultProps" ref="treeRef">
</el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogSetRightVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRight">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            roleList: [],
            rightList: [],
            newRole: {
                roleName: '',
                roleDesc: ''
            },
            editRole: {},
            newRoleRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 6, max: 15, message: '密码长度需在3到15个字符之间', trigger: 'blur' }
                ]
            },
            dialogAddVisible: false,
            dialogEditVisible: false,
            dialogSetRightVisible: false,
            formLabelWitdh: '100px',
            defaultProps: {
                children: 'children',
                label: 'authName'
            },
            defaultKeys: [],
            roleId: '' // 当前即将分配权限的角色id
        }
    },
    created() {
        this.getRoleList()
    },
    methods: {
         async getRoleList() {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.roleList = res.data
        },
        addRole() { // 添加角色
            this.$refs.newRoleRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post('roles', this.newRole)
                if (res.meta.status !== 201) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.dialogAddVisible = false
                this.getRoleList()
            })
        },
        async dialogEditShow(uId, type) { // 打开并查询用户
            this.dialogEditVisible = true
            const { data: res } = await this.$http.get('roles/' + uId)
            if (res.meta.status !== 200) {
                return this.$message.error(res.meta.msg)
            }
            this.editRole = res.data
        },
        dialogAddClose() {
            this.$refs.newRoleRef.resetFields()
        },
        dialogEditClose() {
            this.$refs.editRoleRef.resetFields()
        },
        dialogSetRightClose() {
            this.defaultKeys = []
        },
        handleEdit() {
            this.$refs.editRoleRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put('roles/' + this.editRole.roleId, { roleName: this.editRole.roleName, roleDesc: this.editRole.roleDesc })
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.dialogEditVisible = false
                this.getRoleList()
            })
        },
        handleDelete(uid) { // 删除用户
            this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete('roles/' + uid)
            if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
            }
                this.$message.success(res.meta.msg)
                this.getRoleList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        async removeRightById(role, rightId) {
            var confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            }
            const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
            if (res.meta.status !== 200) {
                return this.$message.error(res.meta.msg)
            }
            this.$message.success(res.meta.msg)
            role.children = res.data
        },
        async dialogSetRightShow(role) {
            this.roleId = role.id
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.rightList = res.data
            this.getLeafKeys(role, this.defaultKeys)
            this.dialogSetRightVisible = true
        },
        getLeafKeys(node, arr) { // 通过递归，获取所有三级权限的id
            if (!node.children) { // 如果当前节点不包含children属性，则说明是三级节点
                return arr.push(node.id)
            }
            node.children.forEach(item => {
                this.getLeafKeys(item, arr)
            })
        },
        async setRight() { // 为角色设置权限
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            console.log(keys)
            const idStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success('分配权限成功！')
            this.getRoleList()
            this.dialogSetRightVisible = false
        }
    }
}
</script>
<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top:1px solid #eee;
    }
    .bdbottom{
        border-bottom: 1px solid #eee
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>